package com.plugin.uniapp;

import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Outline;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.plugin.uniapp.utils.Logger;
import com.plugin.uniapp.video.SurfacePlayer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TextureAdapter extends RecyclerView.Adapter<TextureAdapter.ViewHolder> {
    public static Handler handler = new Handler(Looper.getMainLooper());
    private final int spaceX = 20;
    private final List<String> deviceIds;
    private final int cellWidth, cellHeight;
    private final List<SurfacePlayer> palyers = new ArrayList<>();
    private Map<Integer, ViewHolder> viewList = new HashMap<>();

    public TextureAdapter(List<String> deviceIds) {
        this.deviceIds = deviceIds;
        int screenWidth = Resources.getSystem().getDisplayMetrics().widthPixels;
        this.cellWidth = (screenWidth - spaceX * (Config.Col + 1)) / Config.Col;
        this.cellHeight = (int) (cellWidth * 1.7);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.dialog_video_cell, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        int videoIndex = position;
        String deviceId = deviceIds.get(videoIndex);
        holder.debugText.setText(deviceId);
        viewList.put(videoIndex, holder);

        holder.textureViewBg.getLayoutParams().width = cellWidth;
        holder.textureViewBg.getLayoutParams().height = cellHeight;
        holder.textureViewBg.requestLayout();
        GradientDrawable background = (GradientDrawable) holder.textureViewBg.getBackground();
        if (deviceId.equals(Config.lockedDeviceId)) {
            background.setStroke(7, Color.parseColor("#38CB6C"));
        } else {
            background.setStroke(7, Color.parseColor("#666666"));
        }

        holder.textureView.getLayoutParams().width = cellWidth;
        holder.textureView.getLayoutParams().height = cellHeight;
        holder.textureView.requestLayout();

        holder.textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
                SurfacePlayer player = new SurfacePlayer(new Surface(surface), deviceId);
                palyers.add(player);

                if (videoIndex == 0) {
                    if (Config.CanAutoPopup && (deviceId.equals(Config.lockedDeviceId))) {
                        log("有自动弹的，只联网一个");
                        player.start();
                        handler.postDelayed(() -> {
                           if (!MainActivity.instance.hasSomeonePopup) {
                                log("自动弹出大屏");
                                MainActivity.instance.openDialog(player, deviceIds.get(videoIndex));
                            }
                        }, Config.AutoPopupDelay);
                    } else {
                        //现在是第一台回调，要等100毫秒等待for循环走完，否则当前只有1台
                        handler.postDelayed(() -> {
                            log("无需自动弹大屏，全部" + palyers.size() + "台启动联网");
                                for (int i = 0; i < palyers.size(); i++) {
                                palyers.get(i).start();
                            }
                        }, 100);
                    }
                }

                holder.textureView.setOnClickListener(v -> {
                    log("点击弹出大屏");
                    MainActivity.instance.openDialog(player, deviceIds.get(videoIndex));
                });
            }

            @Override
            public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {
            }

            @Override
            public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {
            }
        });
    }

    @Override
    public int getItemCount() {
        return deviceIds.size();
    }

    public void onDestroy() {
        for (int i = 0; i < palyers.size(); i++) {
            palyers.get(i).stop();
        }
    }

    public void stopAllPlayers(String ignoreDeviceId) {
        for (int i = 0; i < palyers.size(); i++) {
            if (!ignoreDeviceId.equals(palyers.get(i).deviceId)) {
                palyers.get(i).stop();
            }
        }
    }

    public void startAllPlayers() {
        for (int i = 0; i < palyers.size(); i++) {
            palyers.get(i).start();
        }
    }

    private void log(String msg) {
        Logger.log(msg, getClass(), false);
    }

    private void error(String msg) {
        Logger.error(msg, getClass(), false);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        FrameLayout textureViewBg;
        TextureView textureView;
        TextView debugText;
        float radius = 8;

        ViewHolder(View itemView) {
            super(itemView);
            textureViewBg = itemView.findViewById(R.id.texture_view_bg);
            textureView = itemView.findViewById(R.id.texture_view);
            debugText = itemView.findViewById(R.id.debug_device_id);
            textureView.setVisibility(Config.IsDebugMode ? View.VISIBLE : View.GONE);

            // 给 TextureView 设置圆角
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                textureViewBg.setOutlineProvider(new ViewOutlineProvider() {
                    @Override
                    public void getOutline(View view, Outline outline) {
                        outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), radius);
                    }
                });
                textureViewBg.setClipToOutline(true);

                textureView.setOutlineProvider(new ViewOutlineProvider() {
                    @Override
                    public void getOutline(View view, Outline outline) {
                        outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), radius);
                    }
                });
                textureView.setClipToOutline(true);
            }
        }
    }
}